//
//  HKTitleHeaderView.m
//  HKUtilities
//
//  Created by 胡锦涛 on 2018/12/10.
//  Copyright © 2018 胡锦涛. All rights reserved.
//

#import "HKTitleHeaderView.h"
#import "HKTitleButton.h"
@interface HKTitleHeaderView ()
/** 标题下划线 */
@property (nonatomic, strong) UIView *titleUnderline;

@end
@implementation HKTitleHeaderView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupTitleButtons];
        [self setupTitleUnderline];
    }
    return self;
}
/**
 *  标题栏按钮
 */
- (void)setupTitleButtons
{
    // 文字
    NSArray *titles = @[@"作品", @"收藏", @"点赞"];
    NSUInteger count = titles.count;
    
    // 标题按钮的尺寸
    CGFloat titleButtonW = self.width / count;
    CGFloat titleButtonH = self.height;
    
    // 创建5个标题按钮
    for (NSUInteger i = 0; i < count; i++) {
        HKTitleButton *titleButton = [[HKTitleButton alloc] init];
        titleButton.tag = i+1;
        [titleButton addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:titleButton];
        // frame
        titleButton.frame = CGRectMake(i * titleButtonW, 0, titleButtonW, titleButtonH);
        // 文字
        [titleButton setTitle:titles[i] forState:UIControlStateNormal];
        [titleButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [titleButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        
    }
}

/**
 *  标题下划线
 */
- (void)setupTitleUnderline
{
    // 标题按钮
    HKTitleButton *firstTitleButton = self.subviews.firstObject;
    
    // 下划线
    UIView *titleUnderline = [[UIView alloc] init];
    titleUnderline.height = 2;
    titleUnderline.y = self.height - titleUnderline.height;
    titleUnderline.backgroundColor = [firstTitleButton titleColorForState:UIControlStateSelected];
    [self addSubview:titleUnderline];
    self.titleUnderline = titleUnderline;
    
    // 切换按钮状态
    firstTitleButton.selected = YES;
    self.previousClickedTitleButton = firstTitleButton;
    
    [firstTitleButton.titleLabel sizeToFit]; // 让label根据文字内容计算尺寸
    self.titleUnderline.width = firstTitleButton.titleLabel.width + 10;
    self.titleUnderline.centerX = firstTitleButton.centerX;
}

//点击标题按钮
- (void)titleButtonClick:(HKTitleButton *)titleButton
{
    self.previousClickedTitleButton.selected = NO;
    titleButton.selected = YES;
    self.previousClickedTitleButton = titleButton;
    if (self.titleClick) {
        self.titleClick(titleButton);
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.titleUnderline.width = titleButton.titleLabel.width + 20*gScale;
        self.titleUnderline.centerX = titleButton.centerX;
    }];
}
@end
